package logic

import (
	"context"
	"encoding/json"
	"tiktok/model/mysql"
	"tiktok/model/redis"
	"time"

	"tiktok/tiktokrpc/internal/svc"
	"tiktok/tiktokrpc/tiktokrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type TikTokTopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewTikTokTopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TikTokTopListLogic {
	return &TikTokTopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *TikTokTopListLogic) TikTokTopList(in *tiktokrpc.TikTokTopListRequest) (*tiktokrpc.TikTokTopListResponse, error) {
	// todo: add your logic here and delete this line
	var tikTokContents []mysql.TikTokContent

	get := cache.Redis.Get(l.ctx, "tikTokTopList")

	if get.Val() != "" {
		json.Unmarshal([]byte(get.Val()), &tikTokContents)
	} else {
		mysql.DB.Debug().Order("hot desc").Limit(10).Find(&tikTokContents)
		marshal, _ := json.Marshal(tikTokContents)

		cache.Redis.Set(l.ctx, "tikTokTopList", marshal, time.Minute*30)
	}

	var tikTokLists []*tiktokrpc.TikTokTopList

	for _, content := range tikTokContents {
		list := tiktokrpc.TikTokTopList{
			Id:    int64(content.ID),
			Title: content.Title,
			Url:   content.Url,
			Hot:   content.Hot,
		}

		tikTokLists = append(tikTokLists, &list)
	}

	return &tiktokrpc.TikTokTopListResponse{List: tikTokLists}, nil
}
